import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { CSSTransition } from 'react-transition-group';
import { Button } from 'antd';
import Notice from './../Notice';
import UserBox from './../UserBox';
import { connect } from 'react-redux';
import baseURL from './../../config/baseurl';
import jqmlogo from './../../statics/img/jqm-logo.png';
import store from './../../store';
import './index.less';

class Header extends Component {
	
	constructor(props) {
	    super(props);
		this.state={
			focused: false,
			inputValue: "",
			logo: baseURL + "/static/media/system_logo.png"
		}
	}
	
	componentWillUnmount(){
		this.unsubscribe();
	}
	
	componentDidMount(){
		this.unsubscribe = store.subscribe(this.handleStoreChange);
	}
	
	handleStoreChange = () => {
		this.setState({logo: baseURL + "/static/media/system_logo.png?" + Date.now()})
	}

	//全局搜索
	handleSearch = () => {
		const value = this.state.inputValue;
		if(value){
			this.setState({inputValue: ""});
			this.props.search(value);
		}
	}
	
	//logo加载失败
	imgError = () => {
		this.setState({
			logo: jqmlogo
		})
	}
	
	render(){
		const { focused, inputValue, logo } = this.state;
		const menuType = this.props.menuType;
		return (
			<div className="header-wrap">
				<div className="header-left">
					<Link to="/main/whole">
						<div className="logo-wrap">
							<img src={logo} alt="" onError={this.imgError} />
							<h1>JesCloud企业网盘</h1>
						</div>
					</Link>
				</div>
				<div className="header-right">
					<div className="user-wrap" onClick={this.handleUserClick}>
						<UserBox />
					</div>
					<Notice role="wang" />
					{
						menuType?"":
						<div className="search-wrap">
							<CSSTransition
								in={focused}
								timeout={500}
								classNames="slide"
							>
								<input
									placeholder="搜索"
									className={focused ? "focused": ""}
									onChange={ (e)=>this.setState({inputValue: e.target.value}) }
									onFocus={ ()=>this.setState({focused: true}) }
									onBlur={ ()=>this.setState({focused: false}) }
									value={ inputValue }
								/>
							</CSSTransition>
							<Button type="primary" className="search-btn" onClick={this.handleSearch}>搜索</Button>
						</div>
					}
				</div>
			</div>
		)
	}
}

const mapDispatch = (dispatch) => {
	return {
		search(value){
			dispatch({
				type: "SEARCH",
				value
			})
		}
	}
}

export default connect(null,mapDispatch)(Header);